<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JavaScript," />










<meta name="description" content="阅读本文，你能了解到什么？ 笔者将从 链表的简介、单链表相对于数组的优点、怎么创建单链表、如何对单链表进行操作、以及代码实现和分析以下几个方面对链表进行分析，附上源代码，在文章末尾。 1.什么是单链表？单链表是一种链式存取的数据结构，用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的，每个节点的构成：（元素+指针） 元素就是存储数据的存储单元，指针就是连接每个节点的地址数">
<meta property="og:type" content="article">
<meta property="og:title" content="js实现单链表">
<meta property="og:url" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/index.html">
<meta property="og:site_name" content="Chao&#39;s blog">
<meta property="og:description" content="阅读本文，你能了解到什么？ 笔者将从 链表的简介、单链表相对于数组的优点、怎么创建单链表、如何对单链表进行操作、以及代码实现和分析以下几个方面对链表进行分析，附上源代码，在文章末尾。 1.什么是单链表？单链表是一种链式存取的数据结构，用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的，每个节点的构成：（元素+指针） 元素就是存储数据的存储单元，指针就是连接每个节点的地址数">
<meta property="og:locale">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/0.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/1.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/2.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/3.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/4.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/5.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/6.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/7.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/8.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/9.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/10.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/11.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/12.png">
<meta property="article:published_time" content="2022-07-07T10:54:49.000Z">
<meta property="article:modified_time" content="2022-07-07T13:51:36.618Z">
<meta property="article:author" content="Chaoyxy">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/0.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://louchaoyy.gitee.io/blogs/2022/07/07/js实现单链表/"/>





  <title>js实现单链表 | Chao's blog</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chao's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://louchaoyy.gitee.io/blogs/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chao's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">js实现单链表</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-07-07T18:54:49+08:00">
                2022-07-07
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2022/07/07/js实现单链表/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>阅读本文，你能了解到什么？</p>
<p>笔者将从 <strong>链表的简介、单链表相对于数组的优点、怎么创建单链表、如何对单链表进行操作、以及代码实现和分析</strong>以下几个方面对链表进行分析，附上源代码，在文章末尾。</p>
<h2 id="1-什么是单链表？"><a href="#1-什么是单链表？" class="headerlink" title="1.什么是单链表？"></a>1.什么是单链表？</h2><p>单链表是一种链式存取的数据结构，用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的，每个节点的构成：（元素+指针） 元素就是存储数据的存储单元，指针就是连接每个节点的地址数据。</p>
<p>单链表是由一个一个的结点组成的，<strong>可以看成是单链表是手拉手的一群孩子，每个结点就是每个孩子，手就是next指针</strong></p>
<p>单链表的一个结点是这样的</p>
<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/0.png" class title="结点的结构">

<p>单链表最基本的数据结构如下:</p>
<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/1.png" class title="单链表的结构">

<h2 id="2-单链表的优点"><a href="#2-单链表的优点" class="headerlink" title="2.单链表的优点"></a>2.单链表的优点</h2><ul>
<li><p>物理上不连续，但是逻辑上是连续的</p>
</li>
<li><p>任意位置插入删除时间复杂度为**O(1)**。</p>
</li>
<li><p>没有增容问题，插入一个开辟一个空间。</p>
</li>
</ul>
<span id="more"></span>

<h2 id="3-单链表的功能"><a href="#3-单链表的功能" class="headerlink" title="3.单链表的功能"></a>3.单链表的功能</h2><p>我们通过单链表，至少需要实现CRUD四个基本功能</p>
<ul>
<li><p>创建链表</p>
</li>
<li><p>添加元素（头插法，尾插法）</p>
</li>
<li><p>插入元素（指定位置插入元素）</p>
</li>
<li><p>查找某个元素所在的索引</p>
</li>
<li><p>删除元素</p>
</li>
<li><p>获取元素的位置</p>
</li>
<li><p>获取链表的长度</p>
</li>
</ul>
<h2 id="4-创建一个单链表"><a href="#4-创建一个单链表" class="headerlink" title="4.创建一个单链表"></a>4.创建一个单链表</h2><p>在创建单链表之前，笔者先来介绍几个一会儿需要用到的东西</p>
<ul>
<li>头结点：顾名思义链表的最开始的结点</li>
<li>前驱结点：某结点的前一个结点</li>
<li>后继结点：某结点的后一个结点</li>
<li>尾结点：next指针为null的结点</li>
</ul>
<p>如下：</p>
<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/2.png" class title="单链表的各部分结构">

<h2 id="5-结点数据结构"><a href="#5-结点数据结构" class="headerlink" title="5.结点数据结构"></a>5.结点数据结构</h2><p>每个结点包含数据部分和一个<strong>next指针，指向下一个结点</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@name</span>:linkedList</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>:louchao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>:2022/7/7 19:32</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">element</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.data = element;     <span class="comment">//数据data部分</span></span><br><span class="line">        <span class="built_in">this</span>.next = <span class="literal">null</span>;        <span class="comment">//next指针</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="6-链表数据结构"><a href="#6-链表数据结构" class="headerlink" title="6.链表数据结构"></a>6.链表数据结构</h2><p>初始化的时候链表的长度为0，并且头结点都是空的</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//链表</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span> </span>&#123;</span><br><span class="line">    <span class="comment">//构造函数</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.head = <span class="literal">null</span>;       <span class="comment">//初始化头结点置空</span></span><br><span class="line">        <span class="built_in">this</span>.length = <span class="number">0</span>;        <span class="comment">//初始化链表长度为0</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="7-往链表里追加元素-初始化头结点"><a href="#7-往链表里追加元素-初始化头结点" class="headerlink" title="7.往链表里追加元素(初始化头结点)"></a>7.往链表里追加元素(初始化头结点)</h2><p>往链表追加元素就相当于一群小孩准备手拉手做”老鹰捉小鸡“，第一个来的孩子自然是领头的，后面来的只能往他后面站，然后拉着前一个孩子的手，构成了一条链表（尾插法）</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//往链表里面追加元素</span></span><br><span class="line"><span class="function"><span class="title">append</span>(<span class="params">element</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> node = <span class="keyword">new</span> Node(element);   <span class="comment">//新建一个结点</span></span><br><span class="line">    <span class="keyword">let</span> current;                    <span class="comment">//定义一个临时变量，用于遍历链表</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.head === <span class="literal">null</span>)&#123;        <span class="comment">//如果结点为空</span></span><br><span class="line">        <span class="built_in">this</span>.head = node;           <span class="comment">//新来的结点就是头结点</span></span><br><span class="line">    &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">        current = <span class="built_in">this</span>.head;        <span class="comment">//让current从头结点开始</span></span><br><span class="line">        <span class="keyword">while</span> (current.next)&#123;       <span class="comment">//直到current的next指针为空，意味着找到链表尾了</span></span><br><span class="line">            current = current.next; <span class="comment">//往下走</span></span><br><span class="line">        &#125;</span><br><span class="line">        current.next = node;        <span class="comment">//在尾部插入新结点，让尾结点的next指针指向node</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">this</span>.length++;                  <span class="comment">//链表长度+1</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试</p>
<p>往链表里添加2，5，6三个元素</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span>  ll = <span class="keyword">new</span> LinkedList();</span><br><span class="line">ll.append(<span class="number">2</span>);</span><br><span class="line">ll.append(<span class="number">5</span>);</span><br><span class="line">ll.append(<span class="number">6</span>);</span><br></pre></td></tr></table></figure>

<p>结果如下</p>
<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/3.png" class title="往链表里添加元素">

<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/4.png" class title="成功添加3个元素">

<h2 id="8-根据链表索引删除对应的结点"><a href="#8-根据链表索引删除对应的结点" class="headerlink" title="8.根据链表索引删除对应的结点"></a>8.根据链表索引删除对应的结点</h2><p>笔者提供了一个带一个参数的方法，删除对应的结点，参数是想要删除的结点的位置</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据索引删除对应的结点</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param <span class="variable">position</span></span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line"><span class="function"><span class="title">removeAt</span>(<span class="params">position</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (position&gt;-<span class="number">1</span>&amp;&amp;position&lt;<span class="built_in">this</span>.length)&#123;</span><br><span class="line">        <span class="keyword">var</span> current = <span class="built_in">this</span>.head;        <span class="comment">//初始的时候让current指向头结点</span></span><br><span class="line">        <span class="keyword">let</span> index = <span class="number">0</span>;                  <span class="comment">//索引从0开始</span></span><br><span class="line">        <span class="keyword">let</span> previous;                   <span class="comment">//临时变量，用于遍历链表，记录删除的目标结点的前驱结点</span></span><br><span class="line">        <span class="keyword">if</span> (position===<span class="number">0</span>)&#123;              <span class="comment">//如果索引值为0</span></span><br><span class="line">            <span class="built_in">this</span>.head = current.next;   <span class="comment">//直接将头结点设置为原来的头结点的后继结点</span></span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">while</span> (index++<span class="xml">&lt;position)&#123;</span></span><br><span class="line"><span class="xml">                previous = current;     //使previous和cucurrent都指向插入位置的结点</span></span><br><span class="line"><span class="xml">                current = current.next; //current结点往后移动一位</span></span><br><span class="line"><span class="xml">            &#125;</span></span><br><span class="line"><span class="xml">            previous.next = current.next;//目标位置的前驱结点指向后继结点</span></span><br><span class="line"><span class="xml">        &#125;</span></span><br><span class="line"><span class="xml">        this.length--;                   //链表长度-1</span></span><br><span class="line"><span class="xml">        console.log(`被删除的结点是第$&#123;index&#125;个,值为$&#123;current.data&#125;`);</span></span><br><span class="line"><span class="xml">        return current.data;             //返回被删除的结点数据</span></span><br><span class="line"><span class="xml">    &#125;else &#123;</span></span><br><span class="line"><span class="xml">        throw new Error(&quot;out range!&quot;);</span></span><br><span class="line"><span class="xml">    &#125;</span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/5.png" class title="成功的删除索引为2的结点">

<p>删除的过程是这样的</p>
<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/6.png" class title="删除的过程是这样的">

<h2 id="9-指定位置插入新结点"><a href="#9-指定位置插入新结点" class="headerlink" title="9.指定位置插入新结点"></a>9.指定位置插入新结点</h2><p>笔者提供给了一个往链表插入新结点的方法，提供两个参数，第一个参数是索引位置，第二个参数是结点值</p>
<p>插入过程描述：</p>
<ul>
<li>如果索引位置为0，即在头部插入新结点，此时直接把新结点的next指针指向原来的头结点，并且设置新的结点为头结点；</li>
<li>如果索引位置不为0，就进行遍历，找到索引位置之后，此时让current和previous都指向索引结点，current往下延一位，让新结点的next指针指向索引结点的后继（current）,让索引结点的next指针指向新结点，<strong>这个顺序千万不能乱，不然会使previous结点和current结点的链断掉，造成丢失元素，在C/C++语言中会造成野指针和垃圾</strong>，比如一个小孩要玩手拉手的游戏，他要来插队，他应该先找到他后面的同学的手，先拉住后面的同学的手，前面的同学再去主动拉他的手，如果顺序错了，他将找不到集体</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 指定位置插入新结点</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="variable">position</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="variable">element</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="title">insertNode</span>(<span class="params">position,element</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (position&gt;-<span class="number">1</span>&amp;&amp;position&lt;<span class="built_in">this</span>.length)&#123;</span><br><span class="line">        <span class="keyword">let</span> node = <span class="keyword">new</span> Node(element);   <span class="comment">//创建一个新结点</span></span><br><span class="line">        <span class="keyword">let</span> current = <span class="built_in">this</span>.head;        <span class="comment">//初始的时候让current指向头结点</span></span><br><span class="line">        <span class="keyword">let</span> index = <span class="number">0</span>;                  <span class="comment">//索引从0开始</span></span><br><span class="line">        <span class="keyword">let</span> previous;                   <span class="comment">//临时变量，用于遍历链表，记录插入的目标结点的前驱结点</span></span><br><span class="line">        <span class="keyword">if</span> (position===<span class="number">0</span>)&#123;              <span class="comment">//如果索引值为0</span></span><br><span class="line">            node.next = current;        <span class="comment">//先将新结点的next指针指向原来的头结点</span></span><br><span class="line">            <span class="built_in">this</span>.head = node;           <span class="comment">//再把新结点修改为头结点</span></span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">while</span> (index++<span class="xml">&lt;position)&#123;</span></span><br><span class="line"><span class="xml">                previous = current;     //使previous和cucurrent都指向插入位置的结点</span></span><br><span class="line"><span class="xml">                current = current.next; //current结点往后移动一位</span></span><br><span class="line"><span class="xml">            &#125;</span></span><br><span class="line"><span class="xml">            //顺序不能乱，不然会使previous结点和current结点的链断掉，造成丢失元素，在C/C++语言中会造成野指针和垃圾</span></span><br><span class="line"><span class="xml">            node.next = current;        //新结点的next指针指向current</span></span><br><span class="line"><span class="xml">            previous.next = node;       //previous结点的next指针指向新结点</span></span><br><span class="line"><span class="xml">        &#125;</span></span><br><span class="line"><span class="xml">        this.length++;                  //链表长度+1</span></span><br><span class="line"><span class="xml">        return true;</span></span><br><span class="line"><span class="xml">    &#125;else &#123;</span></span><br><span class="line"><span class="xml">        throw new Error(&quot;out range!&quot;);</span></span><br><span class="line"><span class="xml">    &#125;</span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/7.png" class title="在索引为3的地方插入新结点38">

<p>插入结点的过程是这样的</p>
<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/8.png" class title="插入结点的过程">

<h2 id="10-修改指定位置的链表结点的值"><a href="#10-修改指定位置的链表结点的值" class="headerlink" title="10.修改指定位置的链表结点的值"></a>10.修改指定位置的链表结点的值</h2><p>如果需要修改，那怎么做呢？</p>
<p>其实很简单，只要找到某个位置，直接更改值就行</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 修改指定位置的链表结点的值</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="variable">position</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="variable">newval</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="title">updateNode</span>(<span class="params">position,newval</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (position&gt;-<span class="number">1</span>&amp;&amp;position&lt;<span class="built_in">this</span>.length)&#123;</span><br><span class="line">        <span class="keyword">let</span> current = <span class="built_in">this</span>.head;</span><br><span class="line">        <span class="keyword">let</span> index = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">if</span> (position===<span class="number">0</span>)&#123;              <span class="comment">//如果更新的是头结点</span></span><br><span class="line">            current.data = newval;      <span class="comment">//直接更改值就行</span></span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">while</span> (index++<span class="xml">&lt;position)&#123;</span></span><br><span class="line"><span class="xml">                current = current.next;</span></span><br><span class="line"><span class="xml">            &#125;</span></span><br><span class="line"><span class="xml">            current.data = newval;      //进行遍历之后更新值</span></span><br><span class="line"><span class="xml">        &#125;   </span></span><br><span class="line"><span class="xml">        return newval;                  //返回更新的值</span></span><br><span class="line"><span class="xml">                                        //由于更新值不会对链表长度有影响，因此长度不更新</span></span><br><span class="line"><span class="xml">    &#125;else &#123;</span></span><br><span class="line"><span class="xml">        throw new Error(&quot;out range!&quot;);</span></span><br><span class="line"><span class="xml">    &#125;</span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/9.png" class title="更新结点的值的过程">

<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/10.png" class title="更新结点的值的结果">

<h2 id="11-获取指定元素的索引值"><a href="#11-获取指定元素的索引值" class="headerlink" title="11.获取指定元素的索引值"></a>11.获取指定元素的索引值</h2><p>如果该元素存在，则返回索引值</p>
<p>否则，返回-1</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取某值的索引值</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="variable">element</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="title">indexOf</span>(<span class="params">element</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> current = <span class="built_in">this</span>.head;</span><br><span class="line">    <span class="keyword">let</span> index = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (current)&#123;</span><br><span class="line">        <span class="keyword">if</span> (element === current.data)&#123;</span><br><span class="line">            <span class="keyword">return</span> index;</span><br><span class="line">        &#125;</span><br><span class="line">        index++;</span><br><span class="line">        current = current.next;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/11.png" class title="获取指定元素的索引值">

<h2 id="12-遍历链表"><a href="#12-遍历链表" class="headerlink" title="12.遍历链表"></a>12.遍历链表</h2><p>笔者写了该方法，用于获取到链表所有的data</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 遍历链表所有的值</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="title">getListString</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> str = <span class="built_in">this</span>.head.data;</span><br><span class="line">    <span class="keyword">let</span> current = <span class="built_in">this</span>.head.next;</span><br><span class="line">    <span class="keyword">while</span> (current)&#123;</span><br><span class="line">        str += <span class="string">`,<span class="subst">$&#123;current.data&#125;</span>`</span>;</span><br><span class="line">        current = current.next;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> str;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<img src="/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/12.png" class title="遍历链表">

<h2 id="13-获取链表的长度和获取链表的结点"><a href="#13-获取链表的长度和获取链表的结点" class="headerlink" title="13.获取链表的长度和获取链表的结点"></a>13.获取链表的长度和获取链表的结点</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取链表长度</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">&#123;*&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="title">getLength</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.length;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取链表结点</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@returns <span class="type">&#123;null&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="title">getNode</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.head;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="附上源代码"><a href="#附上源代码" class="headerlink" title="附上源代码"></a>附上源代码</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@name</span>:linkedList</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>:louchao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>:2022/7/7 19:32</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">//结点</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">element</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.data = element;     <span class="comment">//数据data部分</span></span><br><span class="line">        <span class="built_in">this</span>.next = <span class="literal">null</span>;        <span class="comment">//next指针</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//链表</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LinkedList</span> </span>&#123;</span><br><span class="line">    <span class="comment">//构造函数</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.head = <span class="literal">null</span>;       <span class="comment">//初始化头结点置空</span></span><br><span class="line">        <span class="built_in">this</span>.length = <span class="number">0</span>;        <span class="comment">//初始化链表长度为0</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//往链表里面追加元素</span></span><br><span class="line">    <span class="function"><span class="title">append</span>(<span class="params">element</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> node = <span class="keyword">new</span> Node(element);   <span class="comment">//新建一个结点</span></span><br><span class="line">        <span class="keyword">let</span> current;                    <span class="comment">//定义一个临时变量，用于遍历链表</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">this</span>.head === <span class="literal">null</span>) &#123;        <span class="comment">//如果结点为空</span></span><br><span class="line">            <span class="built_in">this</span>.head = node;           <span class="comment">//新来的结点就是头结点</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            current = <span class="built_in">this</span>.head;        <span class="comment">//让current从头结点开始</span></span><br><span class="line">            <span class="keyword">while</span> (current.next) &#123;       <span class="comment">//直到current的next指针为空，意味着找到链表尾了</span></span><br><span class="line">                current = current.next; <span class="comment">//往下走</span></span><br><span class="line">            &#125;</span><br><span class="line">            current.next = node;        <span class="comment">//在尾部插入新结点，让尾结点的next指针指向node</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">this</span>.length++;                  <span class="comment">//链表长度+1</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据索引删除对应的结点</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param <span class="variable">position</span></span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="title">removeAt</span>(<span class="params">position</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (position &gt; -<span class="number">1</span> &amp;&amp; position &lt; <span class="built_in">this</span>.length) &#123;</span><br><span class="line">            <span class="keyword">var</span> current = <span class="built_in">this</span>.head;        <span class="comment">//初始的时候让current指向头结点</span></span><br><span class="line">            <span class="keyword">let</span> index = <span class="number">0</span>;                  <span class="comment">//索引从0开始</span></span><br><span class="line">            <span class="keyword">let</span> previous;                   <span class="comment">//临时变量，用于遍历链表，记录删除的目标结点的前驱结点</span></span><br><span class="line">            <span class="keyword">if</span> (position === <span class="number">0</span>) &#123;              <span class="comment">//如果索引值为0</span></span><br><span class="line">                <span class="built_in">this</span>.head = current.next;   <span class="comment">//直接将头结点设置为原来的头结点的后继结点</span></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> (index++ &lt; position) &#123;</span><br><span class="line">                    previous = current;     <span class="comment">//使previous和cucurrent都指向插入位置的结点</span></span><br><span class="line">                    current = current.next; <span class="comment">//current结点往后移动一位</span></span><br><span class="line">                &#125;</span><br><span class="line">                previous.next = current.next;<span class="comment">//目标位置的前驱结点指向后继结点</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">this</span>.length--;                   <span class="comment">//链表长度-1</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`被删除的结点是第<span class="subst">$&#123;index&#125;</span>个,值为<span class="subst">$&#123;current.data&#125;</span>`</span>);</span><br><span class="line">            <span class="keyword">return</span> current.data;             <span class="comment">//返回被删除的结点数据</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&quot;out range!&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 指定位置插入新结点</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param <span class="variable">position</span></span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param <span class="variable">element</span></span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="title">insertNode</span>(<span class="params">position, element</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (position &gt; -<span class="number">1</span> &amp;&amp; position &lt; <span class="built_in">this</span>.length) &#123;</span><br><span class="line">            <span class="keyword">let</span> node = <span class="keyword">new</span> Node(element);   <span class="comment">//创建一个新结点</span></span><br><span class="line">            <span class="keyword">let</span> current = <span class="built_in">this</span>.head;        <span class="comment">//初始的时候让current指向头结点</span></span><br><span class="line">            <span class="keyword">let</span> index = <span class="number">0</span>;                  <span class="comment">//索引从0开始</span></span><br><span class="line">            <span class="keyword">let</span> previous;                   <span class="comment">//临时变量，用于遍历链表，记录插入的目标结点的前驱结点</span></span><br><span class="line">            <span class="keyword">if</span> (position === <span class="number">0</span>) &#123;              <span class="comment">//如果索引值为0</span></span><br><span class="line">                node.next = current;        <span class="comment">//先将新结点的next指针指向原来的头结点</span></span><br><span class="line">                <span class="built_in">this</span>.head = node;           <span class="comment">//再把新结点修改为头结点</span></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> (index++ &lt; position) &#123;</span><br><span class="line">                    previous = current;     <span class="comment">//使previous和cucurrent都指向插入位置的结点</span></span><br><span class="line">                    current = current.next; <span class="comment">//current结点往后移动一位</span></span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">//顺序不能乱，不然会使previous结点和current结点的链断掉，造成丢失元素，在C/C++语言中会造成野指针和垃圾</span></span><br><span class="line">                node.next = current;        <span class="comment">//新结点的next指针指向current</span></span><br><span class="line">                previous.next = node;       <span class="comment">//previous结点的next指针指向新结点</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">this</span>.length++;                  <span class="comment">//链表长度+1</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&quot;out range!&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 修改指定位置的链表结点的值</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param <span class="variable">position</span></span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param <span class="variable">newval</span></span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="title">updateNode</span>(<span class="params">position, newval</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (position &gt; -<span class="number">1</span> &amp;&amp; position &lt; <span class="built_in">this</span>.length) &#123;</span><br><span class="line">            <span class="keyword">let</span> current = <span class="built_in">this</span>.head;</span><br><span class="line">            <span class="keyword">let</span> index = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">if</span> (position === <span class="number">0</span>) &#123;              <span class="comment">//如果更新的是头结点</span></span><br><span class="line">                current.data = newval;      <span class="comment">//直接更改值就行</span></span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> (index++ &lt; position) &#123;</span><br><span class="line">                    current = current.next;</span><br><span class="line">                &#125;</span><br><span class="line">                current.data = newval;      <span class="comment">//进行遍历之后更新值</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> newval;                  <span class="comment">//返回更新的值</span></span><br><span class="line">                                            <span class="comment">//由于更新值不会对链表长度有影响，因此长度不更新</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">&quot;out range!&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取某值的索引值</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param <span class="variable">element</span></span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="title">indexOf</span>(<span class="params">element</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> current = <span class="built_in">this</span>.head;</span><br><span class="line">        <span class="keyword">let</span> index = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span> (current) &#123;</span><br><span class="line">            <span class="keyword">if</span> (element === current.data) &#123;</span><br><span class="line">                <span class="keyword">return</span> index;</span><br><span class="line">            &#125;</span><br><span class="line">            index++;</span><br><span class="line">            current = current.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 遍历链表所有的值</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="title">getListString</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> str = <span class="built_in">this</span>.head.data;</span><br><span class="line">        <span class="keyword">let</span> current = <span class="built_in">this</span>.head.next;</span><br><span class="line">        <span class="keyword">while</span> (current) &#123;</span><br><span class="line">            str += <span class="string">`,<span class="subst">$&#123;current.data&#125;</span>`</span>;</span><br><span class="line">            current = current.next;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> str;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取链表长度</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@returns <span class="type">&#123;*&#125;</span></span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="title">getLength</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.length;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取链表结点</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@returns <span class="type">&#123;null&#125;</span></span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="title">getNode</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.head;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> ll = <span class="keyword">new</span> LinkedList();</span><br><span class="line">ll.append(<span class="number">1</span>)</span><br><span class="line">ll.append(<span class="number">2</span>);</span><br><span class="line">ll.append(<span class="number">3</span>);</span><br><span class="line">ll.append(<span class="number">5</span>);</span><br><span class="line">ll.append(<span class="number">6</span>);</span><br><span class="line"><span class="comment">// ll.removeAt(2);</span></span><br><span class="line">ll.insertNode(<span class="number">3</span>, <span class="number">38</span>);</span><br><span class="line">ll.updateNode(<span class="number">3</span>, <span class="number">48</span>);</span><br><span class="line"><span class="built_in">console</span>.log(ll.indexOf(<span class="number">48</span>));</span><br><span class="line"><span class="built_in">console</span>.log(ll.indexOf(<span class="number">498</span>));</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&quot;遍历链表的结果:&quot;</span>, ll.getListString())</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&quot;获取链表的长度:&quot;</span>, ll.getLength());</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&quot;获取链表的结点:&quot;</span>, ll.getNode());</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(ll);</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/alipay.jpg" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/wechatpay.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2022/07/01/pinia%E7%9A%84%E4%BD%BF%E7%94%A8/" rel="next" title="pinia的使用">
                <i class="fa fa-chevron-left"></i> pinia的使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2022/07/08/js%E5%AE%9E%E7%8E%B0%E6%A0%88-%E9%A1%BA%E5%BA%8F%E6%A0%88%E5%92%8C%E9%93%BE%E6%A0%88/" rel="prev" title="js实现栈-顺序栈和链栈">
                js实现栈-顺序栈和链栈 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a target="_blank" rel="noopener" href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blogs/images/cat.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/louchaoyy" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-gitee"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="louchao@louchaoyy.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E5%8D%95%E9%93%BE%E8%A1%A8%EF%BC%9F"><span class="nav-number">1.</span> <span class="nav-text">1.什么是单链表？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%8D%95%E9%93%BE%E8%A1%A8%E7%9A%84%E4%BC%98%E7%82%B9"><span class="nav-number">2.</span> <span class="nav-text">2.单链表的优点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E5%8D%95%E9%93%BE%E8%A1%A8%E7%9A%84%E5%8A%9F%E8%83%BD"><span class="nav-number">3.</span> <span class="nav-text">3.单链表的功能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E5%8D%95%E9%93%BE%E8%A1%A8"><span class="nav-number">4.</span> <span class="nav-text">4.创建一个单链表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E7%BB%93%E7%82%B9%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="nav-number">5.</span> <span class="nav-text">5.结点数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E9%93%BE%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="nav-number">6.</span> <span class="nav-text">6.链表数据结构</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E5%BE%80%E9%93%BE%E8%A1%A8%E9%87%8C%E8%BF%BD%E5%8A%A0%E5%85%83%E7%B4%A0-%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%B4%E7%BB%93%E7%82%B9"><span class="nav-number">7.</span> <span class="nav-text">7.往链表里追加元素(初始化头结点)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-%E6%A0%B9%E6%8D%AE%E9%93%BE%E8%A1%A8%E7%B4%A2%E5%BC%95%E5%88%A0%E9%99%A4%E5%AF%B9%E5%BA%94%E7%9A%84%E7%BB%93%E7%82%B9"><span class="nav-number">8.</span> <span class="nav-text">8.根据链表索引删除对应的结点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-%E6%8C%87%E5%AE%9A%E4%BD%8D%E7%BD%AE%E6%8F%92%E5%85%A5%E6%96%B0%E7%BB%93%E7%82%B9"><span class="nav-number">9.</span> <span class="nav-text">9.指定位置插入新结点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-%E4%BF%AE%E6%94%B9%E6%8C%87%E5%AE%9A%E4%BD%8D%E7%BD%AE%E7%9A%84%E9%93%BE%E8%A1%A8%E7%BB%93%E7%82%B9%E7%9A%84%E5%80%BC"><span class="nav-number">10.</span> <span class="nav-text">10.修改指定位置的链表结点的值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-%E8%8E%B7%E5%8F%96%E6%8C%87%E5%AE%9A%E5%85%83%E7%B4%A0%E7%9A%84%E7%B4%A2%E5%BC%95%E5%80%BC"><span class="nav-number">11.</span> <span class="nav-text">11.获取指定元素的索引值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-%E9%81%8D%E5%8E%86%E9%93%BE%E8%A1%A8"><span class="nav-number">12.</span> <span class="nav-text">12.遍历链表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#13-%E8%8E%B7%E5%8F%96%E9%93%BE%E8%A1%A8%E7%9A%84%E9%95%BF%E5%BA%A6%E5%92%8C%E8%8E%B7%E5%8F%96%E9%93%BE%E8%A1%A8%E7%9A%84%E7%BB%93%E7%82%B9"><span class="nav-number">13.</span> <span class="nav-text">13.获取链表的长度和获取链表的结点</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%99%84%E4%B8%8A%E6%BA%90%E4%BB%A3%E7%A0%81"><span class="nav-number"></span> <span class="nav-text">附上源代码</span></a></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chaoyxy</span>

  
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>
-->




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/blogs/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://Chaoyxy.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://louchaoyy.gitee.io/blogs/2022/07/07/js%E5%AE%9E%E7%8E%B0%E5%8D%95%E9%93%BE%E8%A1%A8/';
          this.page.identifier = '2022/07/07/js实现单链表/';
          this.page.title = 'js实现单链表';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://Chaoyxy.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
